const express = require("express");
const path = require("path");
const fs = require("fs");
const http = require("http");
const https = require("https");
const cors = require("cors");
const dotenv = require("dotenv");
const { connectToDatabase } = require("./config/db");
const SchedulerService = require("./services/schedulerService");
const authRouter = require("./routes/auth");
const groupsRouter = require("./routes/groups");
const usersRouter = require("./routes/users");
const tasksRouter = require("./routes/tasks");
const notificationsRouter = require("./routes/notifications");
const cookieParser = require("cookie-parser");

dotenv.config();

const app = express();
const PORT = process.env.PORT || 8080;
const HTTPS_PORT = process.env.HTTPS_PORT || 8443;

app.use(
  cors({
    origin: process.env.CORS_ORIGIN || true,
    credentials: true,
  })
);
app.use(cookieParser());
app.use(express.json());
app.set("trust proxy", 1);

// 静态资源代理：前端构建产物目录 html
const staticDir = path.join(__dirname, "..", "html");
app.use(express.static(staticDir));

app.get("/health", (_req, res) => {
  res.status(200).json({ status: "ok" });
});

app.use("/api/auth", authRouter);
app.use("/api/groups", groupsRouter);
app.use("/api/users", usersRouter);
app.use("/api", tasksRouter);
app.use("/api/notifications", notificationsRouter);

// SPA 回退：除 /api/* 以外的请求都返回 index.html
app.get(/^(?!\/api).*/, (req, res) => {
  res.sendFile(path.join(staticDir, "index.html"));
});

async function start() {
  try {
    await connectToDatabase(
      process.env.MONGODB_URI ||
        "mongodb://admin:admin123@127.0.0.1:27017/Task_Manager?authSource=admin"
    );

    // 启动定时任务调度器
    SchedulerService.start();

    const keyPath = process.env.SSL_KEY_PATH;
    const certPath = process.env.SSL_CERT_PATH;
    const pfxPath = process.env.SSL_PFX_PATH; // 可选：PFX 容器
    const caPath = process.env.SSL_CA_PATH; // 可选
    const passphrase = process.env.SSL_PASSPHRASE; // 可选

    if (pfxPath && fs.existsSync(pfxPath)) {
      const httpsOptions = {
        pfx: fs.readFileSync(pfxPath),
        passphrase,
      };

      // 启动 HTTPS 服务（PFX）
      https.createServer(httpsOptions, app).listen(HTTPS_PORT, () => {
        console.log(
          `HTTPS server (PFX) is running at https://localhost:${HTTPS_PORT}`
        );
      });

      // 同时启动一个 HTTP 重定向到 HTTPS
      http
        .createServer((req, res) => {
          const hostHeader = req.headers["host"] || `localhost:${PORT}`;
          const [hostname] = hostHeader.split(":");
          const httpsPortPart =
            Number(HTTPS_PORT) === 443 ? "" : `:${HTTPS_PORT}`;
          const location = `https://${hostname}${httpsPortPart}${req.url}`;
          res.writeHead(301, { Location: location });
          res.end();
        })
        .listen(PORT, () => {
          console.log(
            `HTTP redirect server is running at http://localhost:${PORT}`
          );
        });
    } else if (
      keyPath &&
      certPath &&
      fs.existsSync(keyPath) &&
      fs.existsSync(certPath)
    ) {
      const httpsOptions = {
        key: fs.readFileSync(keyPath),
        cert: fs.readFileSync(certPath),
        passphrase,
      };
      if (caPath && fs.existsSync(caPath)) {
        httpsOptions.ca = fs.readFileSync(caPath);
      }

      // 启动 HTTPS 服务
      https.createServer(httpsOptions, app).listen(HTTPS_PORT, () => {
        console.log(
          `HTTPS server is running at https://localhost:${HTTPS_PORT}`
        );
      });

      // 同时启动一个 HTTP 重定向到 HTTPS
      http
        .createServer((req, res) => {
          const hostHeader = req.headers["host"] || `localhost:${PORT}`;
          const [hostname] = hostHeader.split(":");
          const httpsPortPart =
            Number(HTTPS_PORT) === 443 ? "" : `:${HTTPS_PORT}`;
          const location = `https://${hostname}${httpsPortPart}${req.url}`;
          res.writeHead(301, { Location: location });
          res.end();
        })
        .listen(PORT, () => {
          console.log(
            `HTTP redirect server is running at http://localhost:${PORT}`
          );
        });
    } else {
      // 没有证书则退回到 HTTP
      app.listen(PORT, () => {
        console.log(`HTTP server is running at http://localhost:${PORT}`);
      });
    }
  } catch (err) {
    console.error("启动失败:", err);
    process.exit(1);
  }
}

start();
